package com.notelapierdas.db;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.notelapierdas.exceptions.BusinessAlreadyExistsException;
import com.notelapierdas.exceptions.NoDealsTodayException;
import com.notelapierdas.objects.Business;
import com.notelapierdas.objects.Deal;
import com.notelapierdas.objects.ParcelableDate;
import com.notelapierdas.objects.Price;
import com.notelapierdas.objects.Title;

public class DealDB {
	
	private SQLiteDatabase db;
	private DBHelper helper;

	private static final String TABLE_NAME = "Deal";
	private static final String ID = "_id";
	private static final String TITLE_LONG = "title_long";
	private static final String TITLE_SHORT = "title_short";
	private static final String PRICE_DEAL = "price_deal";
	private static final String PRICE_ORIGINAL = "price_original";
	private static final String DATE = "date";
	private static final String CONDITIONS = "conditions";
	private static final String HIGHLIGHTS = "highlights";
	private static final String BUSINESS_ID = "business";
	private static final String PICTURE = "picture";
	private static final String IS_MAIN_DEAL = "isMainDeal";

	private static final String CREATE_DEALDB = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
			+ TITLE_LONG + " TEXT NOT NULL, " + TITLE_SHORT
			+ " TEXT NOT NULL, " + PRICE_DEAL + " INTEGER NOT NULL, "
			+ PRICE_ORIGINAL + " INTEGER NOT NULL, " + DATE
			+ " INTEGER NOT NULL, " + CONDITIONS + " TEXT NOT NULL, "
			+ HIGHLIGHTS + " TEXT NOT NULL, " + BUSINESS_ID
			+ " INTEGER NOT NULL, " + PICTURE + " BLOB NOT NULL, "
			+ IS_MAIN_DEAL + " INTEGER)";

	public static void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_DEALDB);
	}

	public DealDB(DBHelper helper) {
		this.helper = helper;
	}

	public void open() throws SQLiteException {
		db = helper.getWritableDatabase();
	}

	public void close() {
		helper.close();
	}

	public void saveDeal(Deal d) {
		BusinessDB bdb = new BusinessDB(helper);
		Business b = d.getBusiness();
		try {
			int bID;
			open();
			// Guardo el business
			try{
				
			bID = bdb.saveBusiness(b.getName(), b
					.getAddress().getName(), b.getAddress()
					.getTextCoordinates(), b.getUrl(), d
					.getBusiness().getEmail(), b.getTelephone());
			}catch(BusinessAlreadyExistsException e){
				bID = bdb.getID(b.getName(), b.getAddress().getName());
			}
			
			ContentValues con = new ContentValues();
			con.put(BUSINESS_ID, bID);
			con.put(CONDITIONS, d.getConditions());
			con.put(DATE, d.getEnding_time().getDate().getTime());
			con.put(HIGHLIGHTS, d.getHighlights());
			//con.put(IS_MAIN_DEAL, d.isMainDeal());
			// Guardar imagen
			Bitmap bmp = d.getPicture();
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
			byte[] byteArray = stream.toByteArray();
			con.put(PICTURE, byteArray);
			con.put(PRICE_DEAL, d.getPrice().getDealPrice());
			con.put(PRICE_ORIGINAL, d.getPrice().getOriginalPrice());
			con.put(TITLE_LONG, d.getTitle().getLongTitle());
			con.put(TITLE_SHORT, d.getTitle().getShortTitle());
			
			db.insert(TABLE_NAME, null, con);

		} catch (SQLiteException e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	public ArrayList<Deal> getTodayDeals(ParcelableDate date) throws NoDealsTodayException {
		ArrayList<Deal> list = null;
		try{
			int year = date.getDate().getYear();
			int month = date.getDate().getMonth();
			int day = date.getDate().getDay();
			Date today = new Date(year,month,day);
			Cursor cursor = db.query(TABLE_NAME, null,DATE +" > "+today.getTime(), null, null, null, null);
			cursor.moveToFirst();
			if(cursor.getCount()==0){
				throw new NoDealsTodayException();
			}
			list = new ArrayList<Deal>();
			while(!cursor.isAfterLast()){
				Deal deal = getDealById(cursor.getInt(cursor.getColumnIndex(ID)));
				list.add(deal);
			}
		}catch(SQLiteException e){
			e.printStackTrace();
		}finally{
			close();
		}
		return list;
	}
	
	private Deal getDealById(int id){
		Deal deal = null;
		BusinessDB bdb= new BusinessDB(helper);
		
		try{
			Cursor cursor = db.query(TABLE_NAME, null, ID+"="+id, null, null, null, null);
			cursor.moveToFirst();
			
			String longt = cursor.getString(cursor.getColumnIndex(TITLE_LONG));
			String shortt = cursor.getString(cursor.getColumnIndex(TITLE_SHORT));
			Title title = new Title(longt, shortt);
			//Price
			int dPrice = cursor.getInt(cursor.getColumnIndex(PRICE_DEAL));
			int oPrice = cursor.getInt(cursor.getColumnIndex(PRICE_ORIGINAL));
			Price price = new Price(oPrice, dPrice);
			//Otros atributos
			String conditions = cursor.getString(cursor.getColumnIndex(CONDITIONS));
			String highlights = cursor.getString(cursor.getColumnIndex(HIGHLIGHTS));
			//Business
			Business business = bdb.getBusinessById(cursor.getInt(cursor.getColumnIndex(BUSINESS_ID)));
			//Date
			ParcelableDate date = new ParcelableDate(new Date(cursor.getInt(cursor.getColumnIndex(DATE))));
			//Picture
			byte[]array=cursor.getBlob(cursor.getColumnIndex(PICTURE));
			Bitmap picture = BitmapFactory.decodeByteArray(array, 0	, array.length);
			deal = new Deal(title, price, date, conditions, highlights, business, picture);
			
		}catch(SQLiteException e){
			
		}finally{
			close();
		}
		return deal;
	}

}
